<?php
namespace interface\v1;
/*
*外出接口类
*/

use verify;

class workOutAppClass extends index
{
    private const table = 'work_out';
    private const page = 'workOut';
    private const title = '外出申请';
    public array $stateOption = ['草稿', '审核中', '已通过', '成果审核', '成果确认'];

    /*查询条件*/
    public function search()
    {
        //状态
        $data['result']['stateOption'] = $this->stateOption;
        $data['result']['timeOption'] = $this->timeOption;
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /*列表页*/
    public function list()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            "state" => $this->post('state'),//审批状态
        );
        //初始化
        $and = '';
        if ($this->post('keyword')) {
            $and .= " and (text like '%" . $this->post('keyword') . "%' or orderNo like '%" . $this->post('keyword') . "%')";
        }
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime);
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "expectTimeStart desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $staff = query("staff", "stid = '$array[stid]'");
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'orderNo' => $array['orderNo'],
                "staffName" => $staff['name'],//申请人
                "startTime" => $array['expectTimeStart'],
                'endTime' => $array['expectTimeEnd'],
                "text" => $array['text'],//事由
                "state" => $array['state'],//状态
                'time' => date('m/d', strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 编辑页面
     */
    public function editPage()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        $this->code = 1;
        $data = [];
        if ($id && empty($info['id'])) {
            $this->code = 0;
            $this->resp['warn'] = '未找到此外出申请';
        } elseif (!empty($info['id'])) {
            $data['result'] = [
                'id' => $id,
                'startTime' => $info['expectTimeStart'],
                'endTime' => $info['expectTimeEnd'],
                'text' => $info['text'],
            ];
        }
        $this->resp['data'] = $data;
    }

    /**
     * 编辑成果页面
     */
    public function editResult()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (empty($info['id'])) {
            $this->resp['warn'] = '未找到此外出记录';
        } else {
            $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
            $file = [];
            foreach ($attachFile['array'] as $array) {
                $file[] = [
                    'id' => $array['id'],
                    'name' => $array['name'],
                    'format' => $array['format'],
                    'size' => $array['size'],
                    'src' => self::fillSrc($array['src']),
                    'url' => self::fillSrc($array['src']),
                ];
            }
            $data['result'] = [
                'id' => $id,
                'startFactTime' => $info['timeStart'],
                'endFactTime' => $info['timeEnd'],
                'result' => $info['result'],
                'attachFile' => $file
            ];
            $this->code = 1;
            $this->resp['data'] = $data;
        }

    }

    /**
     * 编辑
     */
    public function commitEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "expectTimeStart" => $this->post('startTime'),
            "expectTimeEnd" => $this->post('endTime'),
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $annotation = [
            "expectTimeStart" => '预计外出时间',
            "expectTimeEnd" => '预计外出时间',
            "text" => '外出事由',
        ];
        $rules = [
            'expectTimeStart' => 'required',
            'expectTimeEnd' => 'required',
            'text' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        } elseif ($field['expectTimeStart'] > $field['expectTimeEnd']) {
            $this->resp['warn'] = "结束时间不得小于开始时间";
        } elseif (sqlNum("work_out", " stid = '" . $this->control['stid'] . "' and timeStart < '$field[expectTimeEnd]' and timeEnd > '$field[expectTimeStart]' and id != '" . $id . "' ") > 0) {
            $this->resp['warn'] = "与其他实际外出时间存在交叉";
        } elseif (empty($info['id'])) {
            $userNo = self::generateCode(self::page,[
                'prefix' => 'WCSQ' . date('Ymd'),
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ],$field);
            $department = query('department', " id = '{$this->controlJob['departmentId']}'");
            $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo, 'state' => '草稿', 'deptName' => $department['name'], 'stid' => $this->control['stid'], "time" => date("Y-m-d H:i:s")));
            $this->resp['warn'] = insert(array("table" => self::table, "field" => $field));
        } else {
            $this->resp['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
        }
        if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            $this->resp['data']['id'] = $id;
            //返回
            $this->code = 1;
        }
        resp:
    }

    public function commitResult()
    {
        $id = $this->post('id');
        //附件
        $fileIdArr = (array)json_decode($_POST['fileId'],true);
        //赋值
        $field = array(
            "timeStart" => $this->post('startTime'),
            "timeEnd" => $this->post('endTime'),
            "result" => $this->post('result'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $annotation = [
            "timeStart" => '实际外出时间',
            "timeEnd" => '实际外出时间',
            "result" => '外出成果',
        ];
        $rules = [
            'timeStart' => 'required',
            'timeEnd' => 'required',
            'result' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        } elseif (strtotime($field['timeEnd']) < strtotime($field['timeStart'])) {
            $this->resp['warn'] = "结束时间不得小于开始时间";
        } elseif (sqlNum("work_out", " stid = '" . $this->control['stid'] . "' and timeStart < '$field[timeEnd]' and timeEnd > '$field[timeStart]' and id != '" . $id . "' ") > 0) {
            $this->resp['warn'] = "与其他实际外出时间存在交叉";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = '未找到此外出记录';
        }elseif($info['state'] !='已通过'){
            $this->resp['warn'] = '此外出申请不是已通过状态，不能编辑成果';
        } else {
            $this->resp['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
        }
        if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            }
            //添加日志
            $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了" . self::title . "成果ID：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //返回
            $this->code = 1;
        }
        resp:
    }

    /*外出记录详情页*/
    public function detail()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '" . $id . "'");
        if (empty($id)) {
            $this->resp['warn'] = "ID为空";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此外出记录";
        } else {
            //申请人
            $staff = query("staff", "stid = '$info[stid]'");
            $flowName = in_array($info['state'], ['已通过', '审核成果', '成果确认']) ? '外出成果审核' : '外出申请';
            $audit = query('audit', "targetId = '$info[id]' and flowName = '$flowName'");
            $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
            $file = [];
            foreach ($attachFile['array'] as $array) {
                $file[] = [
                    'name' => $array['name'],
                    'format' => $array['format'],
                    'size' => self::formatSize($array['size']),
                    'src' => self::fillSrc($array['src']),
                    'url' => self::fillSrc($array['src']),
                ];
            }
            $record = auditAppClass::auditRecord(self::table,$id,$flowName);
            $auditRecord = [];
            $active = 0;
            if ($record !==false){
                $auditRecord = $record['record'];
                $active = $record['active'];
            }
            $data['result'] = [
                'id' => $id,
                'flowName'=>'外出申请',
                'staffName' => $staff['name'],
                'ico' => root . $this->control['ico'] . '?v=' . $this->control['updateTime'],
                'orderNo' => $info['orderNo'],
                'text' => $info['text'],
                'startTime' => $info['expectTimeStart'],
                'endTime' => $info['expectTimeEnd'],
                'startFactTime' => $info['timeStart'],
                'endFactTime' => $info['timeEnd'],
                'outResult' => $info['result'],
                'commitTime' => $audit['commitTime'],
                'deptName' => $info['deptName'],
                'state' => $info['state'],
                'stid' => $info['stid'],
                'attachFile' => $file,
                'role'=>auditAppClass::role(self::table,$id,$flowName),
                'auditRecord'=>$auditRecord,
                'active'=>$active,
                'isResult'=>$flowName=='外出申请'?0:1,
                'flowState'=>$flowName,
            ];
            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的".self::title;
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此".self::title."不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //删除audit表记录
                delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                //删除待办事项
                delete(array("table" => "backlog","where" => " typeId = '$id' "));
                //删除审批记录
                delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                //删除消息提醒
                delete(array("table" => "message","where" => " typeId = '$id' "));
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }
}